package com.tinycloud.miracll.product.service.impl;

import com.tinycloud.common.core.utils.DateUtils;
import com.tinycloud.common.datasource.annotation.Slave4;
import com.tinycloud.miracll.product.domain.*;
import com.tinycloud.miracll.product.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * ERP 排产service
 * 
 * @author tiny
 * @date 2022-05-28
 */
@Service

public class ERPApsServiceImpl implements IERPApsService {

    @Autowired
    IProductScheduleMainService productScheduleMainService;
    @Autowired
    IProductScheduleDetailService productScheduleDetailService;
    @Autowired
    IProductApsScheduleDataService productApsScheduleDataService;
    @Autowired
    IProductApsOrderDataService productApsOrderDataService;
    @Autowired
    IRecipeProdInfoService recipeProdInfoService;
    @Autowired
    IErpProductLineInfoService erpProductLineInfoService;
    @Autowired
    IErpQCMMainService erpQCMMainService;
    @Autowired
    IErpQCLinePackageViewService erpQCLinePackageViewService;
    @Autowired
    IErpQCLineLimitViewService erpQCLineLimitViewService;
    @Autowired
    IProductTypeService productTypeService;

    @Override
    public String geneAPSData(String mainBillNum)  {

        productApsOrderDataService.deleteProductApsOrderDataByMainBillNum(mainBillNum);
        productApsScheduleDataService.deleteProductApsScheduleDataByMainBillNum(mainBillNum);
        ProductScheduleMain productScheduleMain = new ProductScheduleMain();
        productScheduleMain.setNum(mainBillNum);
        List<ProductScheduleMain> productScheduleMainList = productScheduleMainService.selectProductScheduleMainList(productScheduleMain);
        if(null==productScheduleMainList||0==productScheduleMainList.size()) {
            return  "未找到排产表";
        }else {
            productScheduleMain = productScheduleMainList.get(0);
        }
        String rcid = productScheduleMain.getExcelserverrcid();
        String lastNum = productScheduleMain.getLastNum();
        mainBillNum = productScheduleMain.getNum();
        ProductScheduleMain productScheduleMainLast = new ProductScheduleMain();
        productScheduleMainLast.setNum(lastNum);
        productScheduleMainLast = productScheduleMainService.selectProductScheduleMainList(productScheduleMainLast).get(0);
        ProductScheduleDetail productScheduleDetail = new ProductScheduleDetail();
        productScheduleDetail.setExcelserverrcid(rcid);
        List<ProductScheduleDetail> productScheduleDetailList =  productScheduleDetailService.selectProductScheduleDetailList(productScheduleDetail);

        for (ProductScheduleDetail productScheduleDetailTem: productScheduleDetailList ) {
            String scheduleData =  productScheduleDetailTem.getScheduleData();
            if(null!=scheduleData&&!"".equals(scheduleData)) {
                String[] scheduleDatas=  scheduleData.split("-");
                if(scheduleDatas.length<5) {
                    return  "请检查排产数据格式";
                }

            }


        }

        System.out.println(productScheduleDetailList.size());
        for (ProductScheduleDetail productScheduleDetailTem: productScheduleDetailList ) {
            if (null==productScheduleDetailTem.getScheduleData()||"".equals(productScheduleDetailTem.getScheduleData())||"停线".equals(productScheduleDetailTem.getScheduleData())) {
                continue;
            }else {

                ProductApsScheduleData productApsScheduleData = this.geneProductScheduleData(productScheduleDetailTem, productScheduleMainLast);
                productApsScheduleData.setMainBillNum(mainBillNum);

                List<ProductApsOrderData> productApsOrderDataList = this.geneProductApsOrderData(productApsScheduleData);
                System.out.println("========================================================");
                System.out.println(productScheduleDetailTem.getScheduleData());
                System.out.println(productApsScheduleData.toString());
                System.out.println("-----------------------------------------------");
                productApsScheduleDataService.insertProductApsScheduleData(productApsScheduleData);

                for (ProductApsOrderData productApsOrderData :productApsOrderDataList) {
                    productApsOrderDataService.insertProductApsOrderData(productApsOrderData);
                }
                
                if("新增".equals(productApsScheduleData.getEditType())) {
                    String scheduleData = productScheduleDetailTem.getScheduleData();
                    scheduleData = scheduleData+"-"+productApsScheduleData.getScheduleNum();
                    ProductScheduleDetail productScheduleDetailUpdate = new ProductScheduleDetail();
                    productScheduleDetailUpdate.setLineNum(productScheduleDetailTem.getLineNum());
                    productScheduleDetailUpdate.setScheduleDate(productScheduleDetailTem.getScheduleDate());
                    productScheduleDetailUpdate.setScheduleData(scheduleData);
                    productScheduleDetailUpdate.setExcelserverrcid(rcid);
                    productScheduleDetailService.updateProductScheduleDetail(productScheduleDetailUpdate);
                }
            }
        }
        return "success";

    }

    private List<ProductApsOrderData> geneProductApsOrderData(ProductApsScheduleData productApsScheduleData) {

        List<ProductApsOrderData> productApsOrderDataList = new ArrayList<ProductApsOrderData>();
        if ("吨".equals(productApsScheduleData.getUnit())) {
            ProductApsOrderData productApsOrderData = new ProductApsOrderData();
            this.geneProductApsOrderData(productApsScheduleData,productApsOrderData);
            productApsOrderDataList.add(productApsOrderData);
        }else if ("批".equals(productApsScheduleData.getUnit())) {
            Long amount = productApsScheduleData.getAmount().longValue();
            Integer amountInt = amount.intValue();
            for (int i=0;i<amountInt;i++) {
                ProductApsOrderData productApsOrderData = new ProductApsOrderData();
                this.geneProductApsOrderData(productApsScheduleData,productApsOrderData);
                Date scheduleDate = productApsOrderData.getScheduleDate();
                scheduleDate = DateUtils.addDays(scheduleDate,i);
                productApsOrderData.setScheduleDate(scheduleDate);
                productApsOrderDataList.add(productApsOrderData);
            }
        }

        return productApsOrderDataList;
    }

    private void geneProductApsOrderData(ProductApsScheduleData productApsScheduleData, ProductApsOrderData productApsOrderData ) {

        ErpProductLineInfo erpProductLineInfo = new ErpProductLineInfo();
        erpProductLineInfo.setLineNum(productApsScheduleData.getLineNum());
        erpProductLineInfo = erpProductLineInfoService.selectErpProductLineInfoByLineNum(erpProductLineInfo.getLineNum());

        ErpQCLineLimitView erpQCLineLimitView = new ErpQCLineLimitView();
        erpQCLineLimitView.setQcNum(productApsScheduleData.getQcNum());
        erpQCLineLimitView = erpQCLineLimitViewService.selectErpQCLineLimitViewList(erpQCLineLimitView).get(0);

        ErpQCMMain erpQCMMain = new ErpQCMMain();
        erpQCMMain.setQcNum(productApsScheduleData.getQcNum());
        erpQCMMain = erpQCMMainService.selectErpQCMMainByQcNum(erpQCMMain.getQcNum());

        ProductType productType = new ProductType();
        productType.setProdType(erpQCMMain.getProdType());
        productType  = productTypeService.selectProductTypeList(productType).get(0);

        ErpQCLinePackageView erpQCLinePackageView = new  ErpQCLinePackageView();
        erpQCLinePackageView.setQcNum(productApsScheduleData.getQcNum());
        erpQCLinePackageView.setLineNum(productApsScheduleData.getLineNum());
        erpQCLinePackageView.setPackageName(productApsScheduleData.getPackageType());
        List<ErpQCLinePackageView> erpQCLinePackageViewList =  erpQCLinePackageViewService.selectErpQCLinePackageViewList(erpQCLinePackageView);
        if(null!=erpQCLinePackageViewList&&erpQCLinePackageViewList.size()>0) {
            erpQCLinePackageView = erpQCLinePackageViewService.selectErpQCLinePackageViewList(erpQCLinePackageView).get(0);
        }

        productApsOrderData.setScheduleNum(productApsScheduleData.getScheduleNum());
        productApsOrderData.setOrderNum("");
        productApsOrderData.setOperType(productApsScheduleData.getEditType());
        productApsOrderData.setQcNum(productApsScheduleData.getQcNum());
        productApsOrderData.setProductType(erpQCMMain.getProdType());
        productApsOrderData.setLineName(productApsScheduleData.getLineNum());
        productApsOrderData.setScheduleDate(productApsScheduleData.getScheduleDate());
        productApsOrderData.setTypeNum(productType.getTypeNum());
        if("批".equals(productApsScheduleData.getUnit())) {
            productApsOrderData.setMountBatch(productApsScheduleData.getAmount());
            if (null!=productApsScheduleData.getAmountTon()) {
                productApsOrderData.setMountTon(BigDecimal.valueOf(productApsScheduleData.getAmountTon()).divide(productApsScheduleData.getAmount()));
            }
        }else if ("吨".equals(productApsScheduleData.getUnit())&&null!=productApsScheduleData.getAmountTon()) {
            productApsOrderData.setMountTon(BigDecimal.valueOf(productApsScheduleData.getAmountTon()));
        }

        productApsOrderData.setUnit(productApsScheduleData.getUnit());
        productApsOrderData.setPackageNum(erpQCLinePackageView.getPackageNum());
        productApsOrderData.setRemark(productApsScheduleData.getRemark());
        productApsOrderData.setPackageType(productApsScheduleData.getPackageType());
        productApsOrderData.setOrderPurpose("生产");
        if(null!=productApsScheduleData.getRemark()&&productApsScheduleData.getRemark().contains("实验")){
            productApsOrderData.setDevFlag("是");
/*
            productApsOrderData.setOrderPurpose("实验");
*/
        }

       /* productApsOrderData.setElapseTime(new BigDecimal(111));*/
        productApsOrderData.setMark(erpQCMMain.getShopSign());
        productApsOrderData.setTechTpye(erpProductLineInfo.getProcessType());
        productApsOrderData.setLineLimit(erpQCLineLimitView.getLineFormat());
        productApsOrderData.setTypeNum(productType.getTypeNum());
        productApsOrderData.setLineCode(erpProductLineInfo.getLineCode());
        productApsOrderData.setDevice(erpProductLineInfo.getDevice());
        productApsOrderData.setDeviceDept(erpProductLineInfo.getDeviceDeptNum());
        BigDecimal mountKG = productApsOrderData.getMountTon().multiply(BigDecimal.valueOf(1000));
        BigDecimal ourOutput = erpProductLineInfo.getHourOutput();
        if(null!=ourOutput&&0!=ourOutput.longValue())  {
            productApsOrderData.setElapseTime(mountKG.divide(ourOutput,1,BigDecimal.ROUND_HALF_UP));
            if(null!= erpProductLineInfo.getApprovalTime()){
                productApsOrderData.setElapseTime(productApsOrderData.getElapseTime().add(erpProductLineInfo.getApprovalTime()));
            }

        }

        if(null!=productApsOrderData.getLineLimit()&&productApsOrderData.getLineLimit().contains(productApsOrderData.getLineCode())) {
            productApsOrderData.setLineMapFlag("是");
        } else{
            productApsOrderData.setLineMapFlag("否");
        }

        productApsOrderData.setEditDesc(productApsScheduleData.getEditDesc());
        productApsOrderData.setMainBillNum(productApsScheduleData.getMainBillNum());

    }

    private  ProductApsScheduleData geneProductScheduleData(ProductScheduleDetail productScheduleDetail, ProductScheduleMain productScheduleMainLast) {

        ProductApsScheduleData productApsScheduleData  = new ProductApsScheduleData();
        String scheduleData =  productScheduleDetail.getScheduleData();
        String lineNum = productScheduleDetail.getLineNum();
        Date scheduleDate = productScheduleDetail.getScheduleDate();
        productApsScheduleData.setLineNum(lineNum);
        productApsScheduleData.setScheduleDate(scheduleDate);

        productApsScheduleData = this.splitProductScheduleData(productApsScheduleData,scheduleData);
        productApsScheduleData = this.geneProductScheduleDataEditData(productApsScheduleData,productScheduleMainLast);
        productApsScheduleData = this.geneRecipeInfo(productApsScheduleData);

        return  productApsScheduleData;

    }

    private  ProductApsScheduleData splitProductScheduleData(ProductApsScheduleData productApsScheduledata , String scheduleData) {

        String qcNum = null;
        String amount = null;
        String unit = null;
        String packageType = null;
        String remark = null;
        String scheduleNum = null;

        String[] scheduleDatas=  scheduleData.split("-");
        if(scheduleDatas.length==1) {
            qcNum = scheduleDatas[0];
        }if(scheduleDatas.length==2) {
            qcNum = scheduleDatas[0];
            amount = scheduleDatas[1];
        }if(scheduleDatas.length==3) {
            qcNum = scheduleDatas[0];
            amount = scheduleDatas[1];
            unit = scheduleDatas[2];
        }if(scheduleDatas.length==4) {
            qcNum = scheduleDatas[0];
            amount = scheduleDatas[1];
            unit = scheduleDatas[2];
            packageType = scheduleDatas[3];
        }if(scheduleDatas.length==5) {
            qcNum = scheduleDatas[0];
            amount = scheduleDatas[1];
            unit = scheduleDatas[2];
            packageType = scheduleDatas[3];
            remark = scheduleDatas[4];
        }if(scheduleDatas.length==6) {
            qcNum = scheduleDatas[0];
            amount = scheduleDatas[1];
            unit = scheduleDatas[2];
            packageType = scheduleDatas[3];
            remark = scheduleDatas[4];
            scheduleNum = scheduleDatas[5];
        }

        productApsScheduledata.setQcNum(qcNum);
        if (null!=amount) {
            productApsScheduledata.setAmount(BigDecimal.valueOf(Double.valueOf(amount)));
        }

        if("彩包".equals(packageType)) {
            packageType = "彩色包装" ;
        } if("白包".equals(packageType)) {
            packageType = "白色包装";
        }

        productApsScheduledata.setUnit(unit);
        productApsScheduledata.setPackageType(packageType);
        productApsScheduledata.setRemark(remark);
        productApsScheduledata.setScheduleNum(scheduleNum);
        return  productApsScheduledata;
    }


    private  ProductApsScheduleData geneRecipeInfo(ProductApsScheduleData productApsScheduleData ) {
        String lineNum = productApsScheduleData.getLineNum();
        String qcNum = productApsScheduleData.getQcNum();
        RecipeProdInfo recipeProdInfoQuery = new RecipeProdInfo();
        recipeProdInfoQuery.setQcNum(qcNum);
        recipeProdInfoQuery.setLineNum(lineNum);
        List<RecipeProdInfo> recipeProdInfoList = recipeProdInfoService.selectRecipeProdInfoList(recipeProdInfoQuery);
        if ((null!=recipeProdInfoList&&0!=recipeProdInfoList.size())) {
            RecipeProdInfo recipeProdInfo = recipeProdInfoList.get(0);
            productApsScheduleData.setBatchField(recipeProdInfo.getBatchField().longValue());
            if ("批".equals(productApsScheduleData.getUnit())) {
                productApsScheduleData.setAmountTon(productApsScheduleData.getAmount().multiply(recipeProdInfo.getBatchField()).longValue()/1000);
            }

        }else if("吨".equals(productApsScheduleData.getUnit())) {
            productApsScheduleData.setAmountTon(productApsScheduleData.getAmount().longValue());
        }

        ErpQCLineLimitView erpQCLineLimitView = new ErpQCLineLimitView();
        erpQCLineLimitView.setQcNum(productApsScheduleData.getQcNum());
        erpQCLineLimitView = erpQCLineLimitViewService.selectErpQCLineLimitViewList(erpQCLineLimitView).get(0);

        productApsScheduleData.setLineLimit(erpQCLineLimitView.getLineNameFormat());
        if(null!=productApsScheduleData.getLineLimit()&&productApsScheduleData.getLineLimit().contains(productApsScheduleData.getLineNum())) {
            productApsScheduleData.setLineMapFlag("是");
        } else{
            productApsScheduleData.setLineMapFlag("否");
        }

        return  productApsScheduleData;
    }

    private  ProductApsScheduleData geneProductScheduleDataEditData(ProductApsScheduleData productApsScheduleData , ProductScheduleMain productScheduleMainLast) {

        String scheduleNum = productApsScheduleData.getScheduleNum();
        if(null==scheduleNum||"".equals(scheduleNum)) {
            productApsScheduleData.setEditType("新增");
            productApsScheduleData.setEditDesc("新增");
            String mouth = DateUtils.dateTimeNow(DateUtils.YYMM);
            String maxNum = productApsScheduleDataService.selectProductApsScheduleDataMaxMouth(mouth);
            if (null==maxNum) {
                scheduleNum = mouth+"001";
            }else {
                scheduleNum = String.valueOf (Long.valueOf(maxNum)+1);
            }
            productApsScheduleData.setScheduleNum(scheduleNum);
        } else {

            String lastMainBillNum = productScheduleMainLast.getNum();
            ProductApsScheduleData productScheduleDataLast = new ProductApsScheduleData();
            productScheduleDataLast.setMainBillNum(lastMainBillNum);
            productScheduleDataLast.setScheduleNum(scheduleNum);
            List<ProductApsScheduleData> productScheduleDataLastList =  productApsScheduleDataService.selectProductApsScheduleDataList(productScheduleDataLast);
            if(null!=productScheduleDataLastList&&0!=productScheduleDataLastList.size()) {
                productScheduleDataLast = productApsScheduleDataService.selectProductApsScheduleDataList(productScheduleDataLast).get(0);
            }else {

            }

            List<String> editDescList = new ArrayList<String>();

            String lineNum = productApsScheduleData.getLineNum();
            String packageType = productApsScheduleData.getPackageType();
            BigDecimal amount = productApsScheduleData.getAmount();
            String remark = productApsScheduleData.getRemark();
            String scheduleDateString = DateUtils.parseDateToStr(DateUtils.YYYYMMDD,productApsScheduleData.getScheduleDate());

            String lineNumLast = productScheduleDataLast.getLineNum();
            String packageTypeLast = productScheduleDataLast.getPackageType();
            BigDecimal amountLast = productScheduleDataLast.getAmount();
            String remarkLast = productScheduleDataLast.getRemark();
            String scheduleDateLastString = DateUtils.parseDateToStr(DateUtils.YYYYMMDD,productScheduleDataLast.getScheduleDate());

            if (!lineNum.equals(lineNumLast)){
                String descTem = "产线("+lineNumLast+"->"+lineNum+")";
                editDescList.add(descTem);
            }
            if (!packageType.equals(packageTypeLast)){
                String descTem = "包装("+packageTypeLast+"->"+packageType+")";
                editDescList.add(descTem);
            }
            if (0!=amount.compareTo(amountLast)){
                String descTem = "数量("+amountLast+"->"+amount+")";
                editDescList.add(descTem);
            }
            if (!remark.equals(remarkLast)){
                String descTem = "备注("+remarkLast+"->"+remark+")";
                editDescList.add(descTem);
            }
            if (!scheduleDateString.equals(scheduleDateLastString)){
                String descTem = "日期("+scheduleDateLastString+"->"+scheduleDateString+")";
                editDescList.add(descTem);
            }
            String editDesc = new String();
            int i = 0;
            for (String editDescTem : editDescList) {
                if (i<editDescList.size()-1){
                    editDesc = editDesc+editDescTem+"-";
                }else {
                    editDesc = editDesc+editDescTem;
                }
                i++;
            }
            productApsScheduleData.setEditDesc(editDesc);
            if(editDescList.size()==0){
                productApsScheduleData.setEditType("未调整");
            }else{
                productApsScheduleData.setEditType("修改");
            }


        }

        return productApsScheduleData;
    }


}
